<?php

namespace lxs\aliyun;

use AllowDynamicProperties;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use lxs\tools\Tools;
use lxs\tools\Uploads;
use OSS\Core\OssException;
use OSS\Http\RequestCore_Exception;
use OSS\OssClient;

#[AllowDynamicProperties] class OssStorage
{

    public function __construct()
    {
        $this->accessKeyId     = env('ALIYUN_ACCESS_ID');
        $this->accessKeySecret = env('ALIYUN_ACCESS_KEY');
        $this->endpoint        = env('ALIYUN_ENDPOINT');
        $this->bucket          = env('ALIYUN_BUCKET');
    }

    /**
     * 文件上传
     * @param $file
     * @param string $path
     * @return array|false|string
     */
    public function Uploads($file, string $path='images'): array|false|string
    {
        if (!is_file($file)) {
            return false;
        }
        $storage = Storage::disk('aliyunoss');

        $filename = date('ymdHis') . rand(1000, 9999) . '.' . $file->extension();

        $storage->putFileAs($path, $file, $filename);

        return str_replace('https://', 'https://' . $this->bucket . '.', $storage->url($path . '/' . $filename));
    }


    /**
     * base64上传
     * @param $base64
     * @param string $path
     * @param string $type
     * @return array
     * @throws RequestCore_Exception
     */
    public function base64ToOss($base64, string $path = 'images', string $type='wechat'): array
    {
        if ($type == 'wechat') {
            $base64 = Tools::binaryToImage($base64);
        } else if ($type == 'tiktok') {
            $base64 = ('data:image/png;base64,' . $base64);
        }
        // OSS处理
        $result = Uploads::instance()->base64Upload($base64);
        if ($result['code'] != 200) {
            return ['code' => $result['code'], 'oss_url' => false, 'message' => $result['message']];
        }

        $fileResult  = &$result['data'];
        $filePath    = $fileResult['path'] . $fileResult['name'];
        $ossFileName = implode('/', [$path, date('Ymd'), $fileResult['name']]);

        try {

            //实例化对象 将配置传入
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

            $result    = $ossClient->uploadFile($this->bucket, $ossFileName, $filePath);

            $redirectUrl = str_replace('http://', 'https://', $result['info']['url']);

            $localPath = strstr($filePath, 'storage');
            if (Storage::disk('local')->exists($localPath)) {
                Storage::disk('local')->delete($localPath);
            }

            if (!Tools::isImage($redirectUrl)) {
                Log::error('生成小程序码损坏' . PHP_EOL . $redirectUrl);
                return ['code' => 400, 'oss_url' => false];
            }

            return ['code' => 200, 'oss_url' => $redirectUrl];
        } catch (OssException $e) {
            Log::error('base64上传Oss' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL . $e->getFile() . ':' . $e->getLine());
            return ['code' => 400, 'oss_url' => false, 'message' => $e->getMessage()];
        } finally {
            unlink($filePath);
        }
    }




}
